<?php
/**
 * 功能说明：
 * 参数说明：
 * 返回值：
 * 备注说明：
 * 作者：Administrator
 * 最后一次修改时间:2017/5/14 17:16
 */

namespace logic\luckydraw;
use logic\LogicException;
use logic\luckydraw\Prize;
use logic\luckydraw\PrizePoll;
use logic\luckydraw\PrizeTurn;
use core\Rand;
use mod\Travel;
use mod\Zuhesp as zuhespModel;
use mod\Zuhe as zuheModel;
use mod\Lianpiao as lianpiaoModel;
use mod\DynamicPrize;
use mod\Pihao;



class PrizeRules
{
	public $inputData = null;

	public $lianpiaoResult = null;

	public $zuheResult = null;

	public $userInfo = [];

	public $pihaoResult = null;

	public $prizeResutId;

	public $starttime;

	public $endtime;

	public $dynamicRrizeResult = null;

	static public $instance;
	static public function getinstance(){
		if(!self::$instance) self::$instance = new self();
		return self::$instance;
	}

	/*
	 * 信息初始化
	 * $data array
	 * $data['lianpiaono']      抽奖号码
	 * $data['user']            用户信息
	 * $data['lianpiao']  用户信息信息
	 * $data['zuhe']      抽奖规则集合
	 */
	public function format( $data = null ){
		//获取抽奖码相关详细信息
		$this->inputData = $data;
		$this->lianpiaoResult = isset($this->inputData['lianpiao']) ? $this->inputData['lianpiao'] : null;
		$this->zuheResult = isset($this->inputData['zuhe']) ? $this->inputData['zuhe'] : null;
		$this->userInfo = isset($this->inputData['user']) ? $this->inputData['user'] : null;
		$this->pihaoResult = isset($this->inputData['pihao']) ? $this->inputData['pihao'] :null;

		return $this;
	}

	private function getPihao(){
		empty($this->lianpiaoResult) && $this->getLianpiao();

		$this->pihaoResult = Pihao::get($this->lianpiaoResult['pihao_id'])->toArray();
	}

	public function setPihao( $data ){
		$this->pihaoResult = $data;
	}

	private function getLianpiao(){
		if(empty($this->inputData['lianpiaono'])) throw new LogicException('请设置抽奖参数');
		$this->lianpiaoResult = lianpiaoModel::get(['lianpiaono'=>$this->inputData['lianpiaono']])->toArray();
		if(empty($this->lianpiaoResult)) throw new LogicException('抽奖码不存在');
	}

	public function setLianpiao( $data ){
		$this->lianpiaoResult = $data;

		return $this;
	}

	private function getZuhe(){
		empty($this->lianpiaoResult) && $this->getLianpiao();
		$this->zuheResult = zuheModel::get(['id'=>$this->lianpiaoResult['zuhe_id']]);
	}

	public function setZuhe( $data ){
		$this->zuheResult = $data;

		return $this;
	}

	public function setUser( $data ){
		$this->userInfo = $data;

		return $this;
	}

	/*
	 * 执行抽奖操作
	 */
	public function run(){
		//活动是否开始
		$this->isActivityStart();

		//检测是否可以抽奖
		$this->isHaveExtracted();
		//抽奖
		$this->luckydraw();
		//写入奖品订单
		$this->addDynamicPrize();

		return $this;
	}

	/*
	 * 判断活动开始时间
	 */
	public function isActivityStart(){
		empty($this->pihaoResult) && $this->getPihao();

		if(strtotime($this->pihaoResult['activity_starttime']) > time()){
			throw new LogicException("抽奖活动从 {$this->pihaoResult['activity_starttime']} 日开始");
		}
	}

	/*
	 * 获取已经抽取到的奖劵信息
	 */
	private function getDynamicPrize(){
		empty($this->lianpiaoResult) && $this->getLianpiao();
		$this->dynamicRrizeResult = DynamicPrize::where('lianpiaono',$this->lianpiaoResult['lianpiaono'])
			->field('addtime,type,travel_id')
			->select();
	}

	/*
	 * 生成奖劵
	 */
	private function addDynamicPrize(){
		list($starttime,$endtime) = $this->getPeriodOfTime($this->zuheResult['use_date']);
		$data = array();
		$data['uid']                = $this->userInfo['uid'];
		$data['lianpiao_id']        = $this->lianpiaoResult['id'];
		$data['lianpiaono']         = $this->lianpiaoResult['lianpiaono'];
		$data['travel_id']          = $this->prizeResutId;
		$data['addtime']            = date('Y-m-d H:i:s');
		$data['starttime']          = $starttime;
		$data['endtime']            = $endtime;
		$data['zuhe_id']            = $this->lianpiaoResult['zuhe_id'];
		$data['com_id']             = $this->lianpiaoResult['com_id'];
		$data['pihao_id']           = $this->lianpiaoResult['pihao_id'];
		$data['prize_coupon_code'] = Rand::str(20);
		$data['type']               = 0;
		if(!db('dynamic_prize')->insert($data)){
			throw new LogicException('网络异常，请重新打开本页面');
		}
	}

	/*
	 * 检测是否有抽奖资格
	 */
	private function isHaveExtracted(){
		empty($this->dynamicRrizeResult) && $this->getDynamicPrize();
		empty($this->zuheResult) && $this->getZuhe();

		if($this->zuheResult['draw_count'] <= 0){
			throw new LogicException('很遗憾,没有中奖');
			return;
		}
		$totalCount = 0;
		list ($start,$end) = $this->getPeriodOfTime($this->zuheResult['frequency']);
		foreach ($this->dynamicRrizeResult as $d){
			if($d['addtime'] >= $start && $d['addtime'] <= $end && $d['type'] == 0) $totalCount++;
			if($totalCount >= $this->zuheResult['draw_count']){
				throw new LogicException('本周奖品已经领取，不能重复抽奖');
				return;
			}
		}
	}

	/*
	 * 获取时间范围
	 */
	private function getPeriodOfTime($value){
		switch ($value){
			case 'WEEKS':
				$start = date("Y-m-d",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")));
				$end   = date("Y-m-d",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")));
				break;
			case 'MONTH':
				break;
			case 'DAY':
				break;
			default:
				break;
		}
		return [$start,$end];
	}


	/*
	 * 抽奖
	 */
	private function luckydraw(){
		empty($this->dynamicRrizeResult) && $this->getDynamicPrize();
		empty($this->zuheResult) && $this->getZuhe();

		$dynamicLists = array_column($this->dynamicRrizeResult,'travel_id');
		$prizePoll = new PrizePoll();
		$prizeLists = zuhespModel::all(['zuhe_id'=>$this->zuheResult['id'],'random'=>1]);
		if(!empty($prizeLists)){
			foreach ( $prizeLists as $d ) {
				//抽取过的景区不能重复抽取
				if(!in_array($d->travel_id,$dynamicLists)){
					$prizePoll->addItem(new Prize($d->travel_id, $d->probability));
				}
			}
			$turn = new PrizeTurn($prizePoll);
			//抽取的奖品id
			$this->prizeResutId = $turn->run()->getId();
		}else{
			throw new LogicException('领取奖品失败');
		}

	}

	/*
	 * 获取奖品的名称
	 */
	public function getPrizeName(){
		if($this->prizeResutId > 0){
			$title = Travel::where(['aid' => $this->prizeResutId])->value('title');
		}
		return $title;
	}

}